package com.iweibo.ui;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.iweibo.R;
import com.iweibo.bean.UserInfo;
import com.iweibo.bean.WeiboUser;
import com.iweibo.service.UserInfoService;
import com.iweibo.util.NetUtil;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.WeiboParameters;
import com.weibo.sdk.android.net.RequestListener;
import com.weibo.sdk.android.util.Utility;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity {

	private static final String TAG = "WebViewActivity";
	private WebView webView = null;
	private ProgressDialog progressDialog = null;
	
	private static final String CONSUMER_KEY = "4035406520";
	private static final String REDIRECT_URL = "http://www.cdsf.com";
	private Weibo weibo = null;
	private String url = null;
	private WeiboUser weiboUser = null;
	
	private String access_token;
	private String remind_in; 
	private String expires_in;
	private long uid;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		progressDialog = new ProgressDialog(this);
		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//正在加载...
		progressDialog.setMessage(getResources().getText(R.string.loading));
		webView = (WebView) findViewById(R.id.wv_oauth);
		init();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void init() {

		weibo = Weibo.getInstance(CONSUMER_KEY, REDIRECT_URL);
		WeiboParameters parameters = new WeiboParameters();
		parameters.add("forcelogin", "true");
		url = weibo.getAccessAuthorizeUrl(this, parameters);
		Log.d(TAG, "sina weibo url: " + url);
		progressDialog.show();
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl(url);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, "Redirect URL: " + url);
				if (url.startsWith(REDIRECT_URL)) {
					handleRedirectUrl(view, url);
					progressDialog.dismiss();
					return true;
				}
				return super.shouldOverrideUrlLoading(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				Log.d(TAG, "onPageFinished URL: " + url);
				super.onPageFinished(view, url);
				progressDialog.dismiss();
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				Log.d(TAG, "onPageStarted URL: " + url);
				progressDialog.show();
				if (url.startsWith(REDIRECT_URL)) {
					handleRedirectUrl(view, url);
					view.stopLoading();
					progressDialog.dismiss();
					return;
				}
				super.onPageStarted(view, url, favicon);
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					progressDialog.dismiss();
				}
			}
		});
	}

	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);
		String error = values.getString("error");
		String error_code = values.getString("error_code");
		
		if (error == null && error_code == null) {
			access_token = values.getString("access_token");
			remind_in = values.getString("remind_in");
			expires_in = values.getString("expires_in");
			String id = values.getString("uid");
			uid = Long.parseLong(id);
			Log.i(TAG, "access_token:" + access_token);
			Log.i(TAG, "remind_in:" + remind_in);
			Log.i(TAG, "expires_in:" + expires_in);
			Log.i(TAG, "uid:" + uid);
			UserInfoService userInfoService = new UserInfoService(this);
			//获取用户信息...
			progressDialog.setMessage(getResources().getText(R.string.getuserinfo));
			userInfoService.getWeiboUserInfo(access_token, expires_in, uid, listener);
		} else if (error.equals("access_denied")) {
			Log.w(TAG, "用户或授权服务器拒绝授予数据访问权限");
		} else {
			Log.e(TAG, "WeiboException:" + error + "(" + error_code + ")");
		}
	}
	
	/**获取用户信息请求事件*/
	private RequestListener listener = new RequestListener() {
		
		@Override
		public void onError(WeiboException e) {
			Log.e(TAG, "获取用户信息失败:" + e.getMessage() + "|code:" + e.getStatusCode());
		}
		
		@Override
		public void onComplete(String response) {
			try {
				weiboUser = new WeiboUser(new JSONObject(response));
				NetUtil.getNetImageByte(new URL(weiboUser.getProfileImageUrl()), userHeaderPicture);
				//获取用户头像...
				progressDialog.setMessage(getResources().getText(R.string.getuserhead));
			} catch (JSONException e) {
				Log.e(TAG, (String)getResources().getText(R.string.json_exception), e);
			} catch (MalformedURLException e) {
				Log.e(TAG, e.getMessage());
			}
		}
	};
	
	/**获取用户头像的请求事件*/
	private RequestListener userHeaderPicture = new RequestListener() {
		
		@Override
		public void onIOException(IOException e) {
			Log.e(TAG, e.getMessage());
		}

		@Override
		public void onComplete(byte[] response) {
			UserInfo info = new UserInfo(uid, weiboUser.getScreenName(), access_token, 
					Integer.parseInt(remind_in), Integer.parseInt(expires_in), 0, response);
			//保存用户信息...
			progressDialog.setMessage(getResources().getText(R.string.save_user_info));
			saveUser(info);
			Log.d(TAG, "跳转到登录页面");
			Intent intent = new Intent(WebViewActivity.this, LoginActivity.class);
			//是授权页面跳转的
			startActivity(intent);
		}
	};
	
	/**
	 * 保存用户信息
	 * @param info
	 */
	private void saveUser(UserInfo info) {
		UserInfoService userInfoService = new UserInfoService(this);
		boolean res = false;
		//根据用户id查询用户为空则添加用户
		if (null == userInfoService.queryUserInfoById(uid)) {
			res = userInfoService.addUser(info);
			if (res) {
				Log.i(TAG, "添加用户信息成功,UID:" + uid);
			} else {
				Log.i(TAG, "添加用户信息失败");
			}
		} else {
			Log.i(TAG, "用户信息已存在,UID:" + uid);
			res = userInfoService.updateUserInfoById(info);
			if (res) {
				Log.i(TAG, "修改用户信息成功,UID:" + uid);
			} else {
				Log.i(TAG, "修改用户信息失败");
			}
		}
	}
	
}
